﻿const mvc     = require('cosjs.mvc');
const path    = require('path');
const cosjs   = require('cosjs');
//============================启动进程=================================//
let root = path.dirname(process.argv[1]);
let file = path.resolve(root, process.argv[2]||'config');
let options = require(file);



mvc.config.loader.addPath(root+'/share/config');

//游戏环境配置
process.env.NODE_ENV = options.debug ? 'development' : 'production';
mvc.config.set(options);
//初始化MODEL
mvc.model.namespace("admin","branch","redis");
//mvc.handle.namespace("admin");

//本地服务
cosjs.http(options.local);
//脚本服务
cosjs.fork('timer',options["root"]+'/process/timer');
//远程服务
if(options.remote){
    cosjs.http(options.remote);
}
//用户服务 
if(options.service && typeof options.service === 'object'){
    cosjs.http(options.service);
}

//监控服务
if(options.monitor){
    cosjs.fork('monitor',require('cosjs.monitor').server,options.monitor.port,options.monitor);
}

cosjs.start(pool_connect);


function pool_connect(name){
    return Promise.resolve(1).then(()=>{
        return mvc.addPath(options['root']);
    }).then(()=>{
        return cosjs.pool.redis( 'cache',options.dbase.cache);
    }).then(()=>{
        return cosjs.pool.mongodb( 'mongodb',options.dbase.mongodb);
    }).then(()=>{
        if(name==='local' && options.local.monitor && !options.local.monitor.namespace){
            return get_apps_branch();
        }
    }).catch(err=>{
        console.log("pool_connect",err)
    })
}
//开启监控，为所有应用创建监控服务器
function get_apps_branch() {
    let branchModel = mvc.model.admin("branch");
    return branchModel.get(null,["_id","secret"]).then(data=>{
        options.local.monitor.namespace = data;
    })
}